package com.woniu.bh.common.sentinel.exception;

import com.woniu.bh.common.core.exception.ErrorResult;
import com.woniu.bh.common.core.exception.ProjectExceptionResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @version: V1.0
 * @author: Xbao
 * @className: GlobalNoUrlExceptionHandler
 * @packageName: com.woniu.project.common.sentinel.exception
 * @description: 全局找不到资源异常处理器
 * @data: 2020-09-28 9:10
 */
//@RestController
@Slf4j
public class GlobalNoUrlExceptionHandler implements ErrorController {

    private ErrorAttributes errorAttributes;

    public GlobalNoUrlExceptionHandler(ErrorAttributes errorAttributes){
        this.errorAttributes = errorAttributes;
    }

    @Override
    public String getErrorPath(){
        return "/error";
    }

    @GetMapping("/error")
    public ResponseEntity<ErrorResult> exceptionHandler(HttpServletRequest request){
        ServletWebRequest servletWebRequest = new ServletWebRequest(request);
        Map<String,Object> map = errorAttributes.getErrorAttributes(servletWebRequest,true);
        if(map.get("status").equals(404)){
            ErrorResult result = ErrorResult.builder()
                    .code(ProjectExceptionResult.RESOUCE_NOT_FOUND.getCode())
                    .message("找不到资源："+map.get("path").toString())
                    .build();
            log.error("出现异常：code：{},message:{}",404,"找不到资源："+map.get("path").toString());
            ResponseEntity<ErrorResult> resp = new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            return resp;
        }
        ErrorResult result = ErrorResult.builder()
                .code(500)
                .message(map.get("message").toString())
                .build();
        ResponseEntity<ErrorResult> resp = new ResponseEntity<>(result,HttpStatus.INTERNAL_SERVER_ERROR);
        log.error("出现异常：code：{},message:{}",500,map.get("message").toString());
        return resp;
    }
}
